package design.pattern.Lu06ProxyPattern;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @program day01
 * @description: jdk动态代理
 * @author: zhanglu
 * @create: 2019-12-01 22:22:00
 *
 * 需要有实现的接口
 *
 */
public class JdkDynamicProxy {

    public static void main(String[] args) {
//        System.setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
//        Thread thread = new Thread();
//        thread.interrupted();
        Subject02 realSubject = new RealSubject02();

        LuDynamicProxy dynamicProxy = new LuDynamicProxy(realSubject);
        Subject02 subject = (Subject02)Proxy.newProxyInstance(realSubject.getClass().getClassLoader(), new Class[]{Subject02.class}, dynamicProxy);

        subject.request();
        subject.request("111");

    }

}


class LuDynamicProxy implements InvocationHandler {

    private Object object;

    public LuDynamicProxy(Object obj){
        this.object = obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        preHandle();

        Object invoke = method.invoke(object, args);

        endHandle();

        return invoke;
    }

    private void preHandle() {
        System.out.println(" ---> preHandle");
    }

    private void endHandle() {
        System.out.println(" ---> endHandle");
    }

}

interface Subject02{

    void request();

    void request(String id);

}

class RealSubject02 implements Subject02{

    @Override
    public void request() {
        System.out.println(" ---> request");
    }

    @Override
    public void request(String id) {
        System.out.println(" ---> request ---> " + id);
    }
}